from omero import client_wrapper
from omero import gateway
from zope.interface import implements
import logging
from zope.interface import Interface
from pyramid.security import Authenticated
from pyramid.security import Allow


log = logging.getLogger('ampersands.omero')


class IOMERO(Interface):
    pass


class OMERO(object):
    implements(IOMERO)

    __acl__ = [
        (Allow, Authenticated, 'view')
        ]

    def __init__(self, __name__='', __parent__=None, connection=None):
        """
        the base wrapper for the OMERO root object

        Arguments:
        - `self`:
        - `connection`: the omero server connection for the current user
        """
        self.__name__ = __name__
        self.__parent__ = __parent__
        self._connection = connection

    def __getitem__(self, key):
        try:
            project = self._connection.getProject(key)
            project.__parent__ = self
        except ValueError:
            raise KeyError()
        return project

    def values(self):
        return self._connection.listProjects()


class OMEROObjectWrapper(object):
    """
    A wrapper for the Ice Object Like class
    """

    def getType(self):
        return self.__class__.__module__ + '.' + self.__class__.__name__

    def __getitem__(self, oid):
        childw = self._getChildWrapper()

        q = self._conn.getQueryService()
        types = {'Project': 'Dataset', 'Dataset': 'Image'}
        if not self.OMERO_CLASS in types:
            return None
        ds = q.find(types[self.OMERO_CLASS], long(oid))
        if ds is not None:
            ds = childw(self._conn, ds)
        ds.__parent__ = self
        log.info(self)
        log.info(ds)
        return ds

    def values(self):
        return self.listChildren()


class IOMEROImage(Interface):
    pass


class Image(gateway._ImageWrapper, OMEROObjectWrapper):
    """
    A wrapper for the Ice Image class
    """
    implements(IOMEROImage)

gateway.ImageWrapper = Image


class IOMERODataset(Interface):
    pass


class Dataset(gateway._DatasetWrapper, OMEROObjectWrapper):
    """
    A wrapper for the Ice Dataset class
    """
    implements(IOMERODataset)
    __name__ = property(lambda c: str(c.id))


gateway.DatasetWrapper = Dataset


class IOMEROProject(Interface):
    pass


class Project(gateway._ProjectWrapper, OMEROObjectWrapper):
    """
    A wrapper for the Ice Project class
    """
    implements(IOMEROProject)
    __name__ = property(lambda c: str(c.id))


gateway.ProjectWrapper = Project


def get_root(request):
    if 'ampersands.omero' in request.environ:
        blitzcon = request.environ['ampersands.omero']
        omero = OMERO(connection=blitzcon)
        return omero
    return OMERO()
